package com.cp.weixin.blog.service.impl;

import com.cp.weixin.blog.dao.RecordMapper;
import com.cp.weixin.blog.repository.Record;
import com.cp.weixin.blog.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {

	@Autowired
	RecordMapper recordMapper;

	@Override
	public Record getRecordByUrlMd5(String md5) {
		if(StringUtils.isEmpty(md5)) {
			return null;
		}
		return recordMapper.getRecordByUrlMd5(md5);
	}

	@Override
	public int addRecord(String uid, String title, String content, String source, Date pubtime, Date publish_time, String md5, String query, Integer readCount, Integer state, Integer category_id, String tags) {
		return recordMapper.addRecord(uid, title, content, source, pubtime, publish_time, md5, query, readCount, state, category_id, tags);
	}

	@Override
	public int addRecord(Record record, Integer categoryId) {
		String uid = record.getUid();
		String title = record.getTitle();
		String content = record.getContent();
		String source = record.getSource();
		Date pubtime = new Date();
		String md5 = DigestUtils.md5DigestAsHex(title.getBytes());
		String tags = record.getTags();
		return recordMapper.addRecord(uid, title, content, source, pubtime, pubtime, md5, "", 0, 0, categoryId, tags);
	}

	@Override
	public List<Record> getRecordByPageAndStateAndCategoryId(Integer state, Integer categoryId, Integer tagId) {
		return recordMapper.getRecordByPageAndStateAndCategoryId(state, categoryId, tagId);
	}

	@Override
	public Record getRecordByUid(String uid) {
		Record record = recordMapper.getRecordByUid(uid);

		return record;
	}

	public Record getRecordByTitle(String title){
		return recordMapper.getRecordByTitle(title);
	}

	@Override
	public int updateRecord(Record record) {
		return recordMapper.updateRecord(record.getTitle(), record.getSource(), record.getContent(), record.getId());
	}

	/**
	 * 修改并设置state=1
	 * @param record
	 * @return
	 */
	@Override
	public int updateAndPublishRecord(Record record, Integer categoryId) {
		return recordMapper.updateAndPublishRecord(record.getTitle(), record.getSource(), record.getContent(), new Date(), categoryId, record.getId(), record.getTags());
	}

	@Override
	public int readCountPlus(String uid) {
		return recordMapper.readCountPlus(uid);
	}

}
